package com.cn.zengzeng.spbzengzeng.exception;

import com.cn.zengzeng.spbzengzeng.vo.ActionResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @Author: zengzeng
 * @Date: 2021/06/25 0030 22:33
 *
 * 自定义一个基于@Restcontroller的通知
 */
@RestControllerAdvice
public class GlobalControllerAdviser {

    /**
    *
    * @author ZhangZengZeng
    * @date 2023/3/30 17:32
    * @param request request
    * @param e  e
    * @return {@link ActionResult}
    */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ActionResult handlerException(HttpServletRequest request , RuntimeException e){
        return new ActionResult("501",e.getMessage(),null);
    }
    /**
    * 处理所有不可知的异常
    * @author ZhangZengZeng
    * @date 2023/3/30 17:31
    * @param e  e
    * @return {@link ActionResult}
    */
    @ExceptionHandler({Exception.class})
    public ActionResult globalExceptionHandler(Exception e) {
        return new ActionResult("502",e.getMessage(),null);
    }
    /**
    * 自定义异常
    * @author ZhangZengZeng
    * @date 2023/3/30 17:31
    * @param request req
    * @param e e
    * @return {@link ActionResult}
    */
    @ExceptionHandler(MyUnDefindException.class)
    public ActionResult myHandlerException(HttpServletRequest request,MyUnDefindException e){
        return new ActionResult(e.getCode(),e.getMsg(),null);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ActionResult methodArgumentNot(MethodArgumentNotValidException e,HttpServletRequest request){
        return new ActionResult("403",Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage(),null);
    }
}
